package org.wu.framework.smart.platform.start.simple;

import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.JdbcProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.SQLExceptionTranslator;
import org.wu.framework.ssh.server.platform.config.WebSocketConfig;

import javax.sql.DataSource;
import java.util.Objects;

@SpringBootApplication
public class WuSmartPlatformStartSimpleApplication {

    public static void main(String[] args) {
        SpringApplication.run(WuSmartPlatformStartSimpleApplication.class, args);
    }

    @Bean
    public JdbcProperties jdbcProperties() {
        return new JdbcProperties();
    }


    @Bean
    @Primary
    JdbcTemplate jdbcTemplate(DataSource dataSource, JdbcProperties properties, ObjectProvider<SQLExceptionTranslator> sqlExceptionTranslator) {
        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
        JdbcProperties.Template template = properties.getTemplate();
        jdbcTemplate.setIgnoreWarnings(template.isIgnoreWarnings());
        jdbcTemplate.setFetchSize(template.getFetchSize());
        jdbcTemplate.setMaxRows(template.getMaxRows());
        if (template.getQueryTimeout() != null) {
            jdbcTemplate.setQueryTimeout((int)template.getQueryTimeout().getSeconds());
        }

        jdbcTemplate.setSkipResultsProcessing(template.isSkipResultsProcessing());
        jdbcTemplate.setSkipUndeclaredResults(template.isSkipUndeclaredResults());
        jdbcTemplate.setResultsMapCaseInsensitive(template.isResultsMapCaseInsensitive());
        Objects.requireNonNull(jdbcTemplate);
        sqlExceptionTranslator.ifUnique(jdbcTemplate::setExceptionTranslator);
        return jdbcTemplate;
    }
}
